package com.wangxq.loginmodule.yd_login.login.mvp.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.delegate.sys.LoginBean;
import com.jess.arms.base.delegate.sys.LoginReponsBody;
import com.jess.arms.base.delegate.sys.LoginStateUtil;
import com.jess.arms.base.delegate.sys.SysInfo;
import com.jess.arms.database.MMkvHelper;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.orhanobut.logger.Logger;
import com.tencent.mmkv.MMKV;
import com.wangxq.loginmodule.R;
import com.wangxq.loginmodule.yd_login.SoftKeyboardManager;
import com.wangxq.loginmodule.yd_login.login.di.component.DaggerLoginComponent;
import com.wangxq.loginmodule.yd_login.login.di.module.LoginModule;
import com.wangxq.loginmodule.yd_login.login.mvp.contract.LoginContract;
import com.wangxq.loginmodule.yd_login.login.mvp.presenter.LoginPresenter;
import com.wangxq.mylibrary.dialog.DialogTools;
import com.zhy.autolayout.AutoLinearLayout;
import com.zlx.widget.text.ClearEditText;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View,SoftKeyboardManager.SoftKeyboardStateListener {
    @Inject
    LoginPresenter mPresenter;
    /**
     * 图片logo
     */
    ImageView imgLogo;
    /**
     * 标题1
     */
    TextView tvTitle1;
    /**
     * 标题2
     */
    TextView tvTitle2;
    /**
     * 用户名
     */
    ClearEditText usernameText;
    /**
     * 清除用户
     */
    ImageView ivDelete;
    /**
     * 用户栏
     */
    LinearLayout inputAccount;
    /**
     * 密码
     */
    ClearEditText passwordText;
    /**
     * 登录
     */
    Button loginBtn;
    /**
     * 记住账号
     */
    CheckBox rememberAccount;
    /**
     * 设置
     */
    TextView settingTxv;
    /**
     * 版本
     */
    TextView version;
    /**
     * 用户集合
     */
    List<String> users = new ArrayList<>();
    /**
     * 用户弹窗
     */
    PopupMenu popupMenu;
    /**
     * 下拉按钮
     */
    ImageView ivSpring;
    /**
     * 公司名字
     */
    TextView tvCompanyName;
    /**
     * 是否离线
     */
    CheckBox cbOffline;
    private SoftKeyboardManager softKeyboardManager;
    private AutoLinearLayout llBg;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        return R.layout.activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initViews();
        llBg=findViewById(R.id.llBg);
        softKeyboardManager = new SoftKeyboardManager(llBg);
        softKeyboardManager.addSoftKeyboardStateListener(this);
//        StateUtils.setLightStatusBar(this, true);// 设置状态栏字体颜色为黑色
        Log.e("尺寸", ScreenUtils.getScreenWidth() + "" + ScreenUtils.getScreenHeight() + ScreenUtils.getScreenDensityDpi());
        popupMenu = new PopupMenu(this, inputAccount);
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                usernameText .setText(item.getTitle());
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(inputAccount.getWindowToken(), 0);
                }
                popupMenu.dismiss();
                return false;
            }
        });

        if(users.size()>0){
            usernameText.setText(users.get(0));
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
            if (!checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.REQUEST_INSTALL_PACKAGES,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_STORAGE);
            }
        }
        findViewById(R.id.imgLogo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            mPresenter.test();
            }
        });

        passwordText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect =new Rect();
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);//获取当前界面可视部分
                int screenHeight = getWindow().getDecorView().getRootView().getHeight();//获取屏幕高度
                int heiDifference = screenHeight - rect.bottom;//获取键盘高度，键盘没有弹出时，高度为0，键盘弹出时，高度为正数
            }
        });

    }

    /**
     * 绑定业务
     */
    private void initViews() {
        imgLogo=findViewById(R.id.imgLogo);
        tvTitle1=findViewById(R.id.tvTitle1);
        tvTitle2=findViewById(R.id.tvTitle2);
        usernameText=findViewById(R.id.usernameText);
        ivDelete=findViewById(R.id.ivDelete);
        inputAccount=findViewById(R.id.input_account);
        passwordText=findViewById(R.id.passwordText);
        loginBtn=findViewById(R.id.loginBtn);
        rememberAccount=findViewById(R.id.rememberAccount);
        settingTxv=findViewById(R.id.settingTxv);
        version=findViewById(R.id.version);
        ivSpring=findViewById(R.id.ivSpring);
        tvCompanyName=findViewById(R.id.tvCompanyName);
        cbOffline=findViewById(R.id.cbOffline);
        clicks();
        /**
         * https://blog.csdn.net/weixin_36127082/article/details/117311826
         * 默认数字键盘
         */
        usernameText.setRawInputType(Configuration.KEYBOARD_QWERTY);
        passwordText.setRawInputType(Configuration.KEYBOARD_QWERTY);
    }

    /**
     * 点击始键相关
     */
    private void clicks(){
        if (0!=MMkvHelper.getInstance().getAppLogo()){
            imgLogo.setImageResource(MMkvHelper.getInstance().getAppLogo());
        }
        tvTitle1.setText(TextUtils.isEmpty(MMkvHelper.getInstance().getAppName())?tvTitle1.getText(): MMkvHelper.getInstance().getAppName());
        tvCompanyName.setText(TextUtils.isEmpty(MMkvHelper.getInstance().getCompanyName())?tvCompanyName.getText(): MMkvHelper.getInstance().getCompanyName());
        version.setText(TextUtils.isEmpty(MMkvHelper.getInstance().getAppVersion())?version.getText():MMkvHelper.getInstance().getAppVersion());
        //登录始键
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (usernameText.getText() == null || StringUtils.isTrimEmpty(usernameText.getText().toString())) {
                    ToastUtils.showShort("请输入用户名！");
                    return;
                }
                if (passwordText.getText() == null || StringUtils.isTrimEmpty(passwordText.getText().toString())) {
                    ToastUtils.showShort("请输入密码！");
                    return;
                }

                //判断在线还是离线模式
                if(cbOffline.isChecked()){
                    String uNameAndPwd = CacheDiskUtils.getInstance().getString("uNameAndPwd");

                    if(TextUtils.isEmpty(uNameAndPwd)){
                        ToastUtils.showShort("账号暂无登录记录！");
                        return;
                    }

                    LoginBean loginBean= new Gson().fromJson(uNameAndPwd,LoginBean.class);
                    String userLoginBody = MMkvHelper.getInstance().getString("userLoginBody");
                    LoginReponsBody userInfo =new Gson().fromJson(userLoginBody,LoginReponsBody.class);
                    if(userInfo==null){
                        Logger.e("学生信息为空");
                    }else {
                        Logger.e("学生信息不为空"+new Gson().toJson(userInfo));
                    }


                    if(!usernameText.getText().toString().equals(loginBean.uName)){
                      showMessage("请输入上次登录账号！");
                      return;
                    }
                    if(!passwordText.getText().toString().equals(loginBean.pwd)){
                        showMessage("请输入上次登录密码！");
                        return;
                    }
                    toMainActivity();

                }else {
                    String loginUrl = MMkvHelper.getInstance().getLoginUrl();
                    if (rememberAccount.isChecked()) {
                        mPresenter.Login(loginUrl,usernameText.getText().toString(), passwordText.getText().toString(), true);
                    } else {
                        mPresenter.Login(loginUrl,usernameText.getText().toString(), passwordText.getText().toString(), false);
                    }
                }


            }
        });
        //前往设置页面
        settingTxv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArmsUtils.startActivity(new Intent(LoginActivity.this, SettingActivity.class));
            }
        });
        //下拉选择人员
        ivSpring.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(users.size()>0){
                    android.view.Menu menu_more = popupMenu.getMenu();
                    menu_more.clear();
                    int size = users.size();
                    for (int i = 0; i < size; i++) {
                        menu_more.add(android.view.Menu.NONE,  i, i, users.get(i));
                    }
                    popupMenu.show();
                }else {
                    ToastUtils.showShort("无保存用户信息");
                }
            }
        });
    }

    /**
     * 检测权限
     */
    public  int REQUEST_PERMISSION_STORAGE = 0x01;
    private boolean checkPermission(@NonNull String permission) {
        return ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
    }
    @Override
    public void showLoading() {
        DialogTools.INSTANCE.showLoading(getSupportFragmentManager());
    }

    @Override
    public void hideLoading() {
        DialogTools.INSTANCE.dismissLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ToastUtils.showShort(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    /**
     * 前往主页
     */
    @Override
    public void toMainActivity() {
        String mainClass= MMkvHelper.getInstance().getMainUrl();
        try {
            Class mainClassInfo=Class.forName(mainClass);
            Intent intent=new Intent();
            intent.setClass(LoginActivity.this,mainClassInfo);
            startActivity(intent);
            finish();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 每次onResum时获取最新user成员
     */
    @Override
    protected void onResume() {
        super.onResume();
        users.clear();
        ArrayList<String> list = (ArrayList<String>) CacheDiskUtils.getInstance().getSerializable("users");
        if (list != null && list.size() > 0) {
            users.addAll(list);
        }
    }

    @Override
    public void onSoftKeyboardOpened(int keyboardHeightInPx) {
        if (SoftKeyboardManager.DEBUG){
            Log.d(TAG, "keyboardOpened, keyboardHeightInPx = "+keyboardHeightInPx);
        }
        Rect rect = new Rect();
        //获取root在窗体的可视区域
        llBg.getWindowVisibleDisplayFrame(rect);
        //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
        int rootInvisibleHeight = llBg.getRootView().getHeight() - rect.bottom;
        //若不可视区域高度大于100，则键盘显示
        if (rootInvisibleHeight > 100) {
            int[] location = new int[2];
            //获取focusedView在窗体的坐标
            View focusedView = getCurrentFocus();
            if (focusedView instanceof EditText){
                focusedView.getLocationInWindow(location);
                int focusedViewPosY = location[1] + focusedView.getHeight();
                if (SoftKeyboardManager.DEBUG){
                    Log.d(TAG, "rect.bottom= "+rect.bottom+", focusedViewPosY = "+focusedViewPosY);
                    Log.i(TAG, "focused view need scroll up or down");
                }
                int srollHeight = focusedViewPosY - rect.bottom;
                if (SoftKeyboardManager.DEBUG){
                    Log.i(TAG, "srollHeight = "+srollHeight);
                }
                if (srollHeight>0) {//焦点被输入法遮挡,View向上滚动
                    llBg.scrollTo(0, srollHeight);
                }
            }
        }
    }

    @Override
    public void onSoftKeyboardClosed() {
        if (SoftKeyboardManager.DEBUG){
            Log.d(TAG, "keyboardClosed ");
        }
        //输入法退出，root滚动到初始位置
        llBg.scrollTo(0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        softKeyboardManager.removeSoftKeyboardStateListener(this);
        softKeyboardManager.dispose();
    }

}
